package org.llc.gof.creator.prototype.deep;

import java.io.*;

public class Student implements Cloneable, Serializable {

	private static final long serialVersionUID = 1L;
	private String name;
	private int age;
	private Dates birthday;

	public Student() {
		super();
	}

	public Student(String name, int age, Dates birthday) {
		super();
		this.name = name;
		this.age = age;
		this.birthday = birthday;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Dates getBirthday() {
		return birthday;
	}

	public void setBirthday(Dates birthday) {
		this.birthday = birthday;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", birthday=" + birthday + "]";
	}

	/**
	 * 完成浅克隆类需实现Cloneable接口
	 */
	public Object shallowClone(Student student) {
		try {
			return student.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 完成深克隆被克隆的类和类的引用类 均实现Serializable接口
	 */
	public Object deepClone(Student student) {
		/*
		 * 本次实现深克隆使用 ByteArrayOutputStream 和ByteArrayInputStream 作为复制过程中字符数组存储中介
		 */
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		ObjectInputStream ois;
		try(ObjectOutputStream oos = new ObjectOutputStream(bos)) {
			// 将bos作为收集字节数组中介
//			oos = new ObjectOutputStream(bos);
			// 将传入参数student类写入bos中
			oos.writeObject(student);
			// 将读取到数据传入ObjectInputStream
			ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
			return ois.readObject();
		} catch (IOException | ClassNotFoundException e) {
			return null;
		}
	}

	public static void main(String[] args) {
		Student student = new Student("小强", 21, new Dates("1997", "06", "13"));
		System.out.println("原student类   " + student);
		// 浅克隆对象shallowCloneStudent
		Student shallowCloneStudent = (Student) student.shallowClone(student);
		System.out.println("浅克隆出来的student   " + shallowCloneStudent);
		System.out.println("浅克隆和深克隆对象对比   " + shallowCloneStudent.equals(student));
		System.out
				.println("浅克隆Date和深克隆Date类引用是否相同   " + shallowCloneStudent.getBirthday().equals(student.getBirthday()));
		// 深克隆对象deepCloneStudent
		Student deepCloneStudent = (Student) student.deepClone(student);
		System.out.println("深克隆出来的student   " + deepCloneStudent);
		System.out.println("深克隆和深克隆对象对比   " + deepCloneStudent.equals(student));
		System.out.println("深克隆Date和深克隆Date类引用是否相同   " + deepCloneStudent.getBirthday().equals(student.getBirthday()));

	}
}
